package com.akami.news;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import xframe.ctl.XDispatchAction;
import xframe.util.UtilMaster;
import xframe.util.db.Row;
import xframe.util.db.Transaction;

public class NewsAction extends XDispatchAction {
	public ActionForward move( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception { 

		Row	req			=	getRequestInfo(request);
		
		
		
		
		return mapping.findForward((String) req.get("NEXT_PAGE") );
	}
	
	// 리스트
	public ActionForward selectCode( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {

		Row	req			=	getRequestInfo(request);
			

		try{
			// 디비연결 시작
			Transaction.start(request);		
			
			HttpSession session = request.getSession();
			req.put("s_name", session.getAttribute("name"));
			req.put("s_email", session.getAttribute("email"));
			
	        // 전체 게시물 갯수
			String totalQueryName	=	"codeMaster.codeCnt";		
			String	totalQuery 	=	mappingQuery(request, totalQueryName);
			
			simpleExecuteQueryGetOneRow(request, totalQuery, totalQueryName);
			
			Row	SUM_LIST	=	(Row)request.getAttribute(totalQueryName);			
			req.put("TOTAL", SUM_LIST.getString("TOTAL"));					
			int start_row 	=	0;
			int page		=	0;
			//페이지 파라미터 점검
			//첫페이지는 파라미터가 없으므로 0이나 1로 셋팅한다.
			if(req.get("page") ==null || ((String)req.get("page")).trim().length() == 0 ){
				page	=	1;
			}else  {
				try{
					page	=	Integer.parseInt(((String)req.get("page")));
				}catch(Exception e){
					page	=	1;
				}
			}
			start_row	=	(page	-	1)	*	10;
			req.put("start_row", start_row+"");
			req.put("page", page+"");
			
			//전체게시물의 갯수를 토대로 다시 쿼리를 날려서 원하는 데이터만 받아온다.		
			String 	listQueryName	=	"codeMaster.selectCode";
			String	listQuery 		=	mappingQuery(req, listQueryName);	
	
			simpleExecuteQuery(request, listQuery, listQueryName);												
	
			//디비연결 종
	        Transaction.end(request);
        
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.toString());
			return mapping.findForward( "system_error" );
		}        
		
        return mapping.findForward( "selectCode" );       
	}
	
	
	
	
	public ActionForward getNews( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
			Row	req			=	getRequestInfo(request);
		try{
			// 디비연결 시작
			Transaction.start(request);		
			
			String 	listQueryName	=	"newsMaster.getNews";
			String	listQuery 		=	mappingQuery(req, listQueryName);	
			Row resultRow = simpleExecuteQueryGetOneRow(request, listQuery, listQueryName);												
	        
			
			listQueryName	=	"newsMaster.getKeyword";
			listQuery 		=	mappingQuery(req, listQueryName);	
			simpleExecuteQuery(request, listQuery, listQueryName);												
			
			
			request.setAttribute("resultRow",resultRow);
			//디비연결 종
	        Transaction.end(request);
        
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		}    		
	return mapping.findForward("getNews");
	}
	
	public ActionForward newsPreview( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		Row	req			=	getRequestInfo(request);
		try{
			// 디비연결 시작
			Transaction.start(request);		
			
			String 	listQueryName	=	"newsMaster.newsPreview";
			String	listQuery 		=	mappingQuery(req, listQueryName);	
			Row resultRow = simpleExecuteQueryGetOneRow(request, listQuery, listQueryName);												
			
			
			listQueryName	=	"newsMaster.newsPreviewKeyword";
			listQuery 		=	mappingQuery(req, listQueryName);	
			simpleExecuteQuery(request, listQuery, listQueryName);												
			
			
			request.setAttribute("resultRow",resultRow);
			//디비연결 종
			Transaction.end(request);
			
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		}    		
		return mapping.findForward("newsPreview");
	}
	
	
	public ActionForward newsInsert( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		try{		
		// 디비연결 시작
		Transaction.start(request);		
		
		HttpSession session = request.getSession();
		req.put("reg_email", session.getAttribute("s_email"));
		req.put("upd_email", session.getAttribute("s_email"));
		req.put("upd_tel", session.getAttribute("s_tel"));
		

		String queryName	=	"newsMaster.insert";		
		String news_idx		=	System.nanoTime()+"";
		req.put("news_idx",news_idx);
		req.put("sisa",req.getString("sisa").replaceAll("\n", "<br>"));
		
		//req.get(UtilMaster.convertHtml(req.getString("title")));
		//req.get(UtilMaster.convertHtml(req.getString("headline")));
		
		String	query 	=	mappingQuery(req, queryName);
		String[] preparedIndex = {
				"news_idx",            
				"part_code",            
				"ref_url",            
				"ref_date",            
				"title",            
				"sisa",            
				"headline",            
				"content_html",            
				"ref_code",            
				"reg_name",            
				"reg_email",            
				"reg_name",            
				"upd_email",            
				"upd_tel"            
				};
		//PreparedStatement  실행
		preparedExecuteUpdate(request, req, preparedIndex, query);	
		
		
		queryName	=	"newsMaster.insertKeyword";	
		
		
		
		String[] keyword = (String[])req.get("ref_keyword");
		
		
		for(int i =0 ; i < keyword.length ; i++){
			req.put("ref_keyword",keyword[i]);
			query 	=	mappingQuery(req, queryName);
			simpleExecuteUpdate(request, query, queryName);
		}
		
		request.setAttribute("nextPage", request.getContextPath()+"/news.do?command=select");

		//디비연결 종
        Transaction.end(request);
												
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		} 
		
		return mapping.findForward("sendRedirect");
	}
	
	
	public ActionForward updateNews( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		try{		
			// 디비연결 시작
			Transaction.start(request);		
			
			HttpSession session = request.getSession();
			req.put("reg_email", session.getAttribute("s_email"));
			req.put("upd_email", session.getAttribute("s_email"));
			

			//req.get(UtilMaster.convertHtml(req.getString("title")));
			//req.get(UtilMaster.convertHtml(req.getString("headline")));
			//req.put("sisa",req.getString("sisa").replaceAll("\n", "<br>"));
			
			String queryName	=	"newsMaster.updateNews";		
			
			String	query 	=	mappingQuery(req, queryName);

			String[] preparedIndex = {
					"part_code",            
					"status_code",            
					"ref_code",            
					"ref_url",            
					"ref_date",            
					"title",            
					"sisa",            
					"headline",            
					"content_html",            
					"news_code",            
					"upd_name",            
					"upd_email",            
					"upd_tel" ,          
					"news_idx"            
			};
			//PreparedStatement  실행
			preparedExecuteUpdate(request, req, preparedIndex, query);	
			
			
			queryName	=	"newsMaster.deleteKeywordOne";	
			query 	=	mappingQuery(req, queryName);
			simpleExecuteUpdate(request, query, queryName);
			
			
			
			queryName	=	"newsMaster.insertKeyword";	
			
			String[] keyword = (String[])req.get("ref_keyword");
			for(int i =0 ; i < keyword.length ; i++){
				if(keyword[i].trim().length() > 0){
				req.put("ref_keyword",keyword[i]);
				query 	=	mappingQuery(req, queryName);
				simpleExecuteUpdate(request, query, queryName);
				}
			}		
			
			
			request.setAttribute("nextPage", request.getContextPath()+"/news.do?command=select");
			
			//디비연결 종
			Transaction.end(request);
			
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		} 
		
		return mapping.findForward("sendRedirect");
	}
	
	public static void charSet(String str_kr) throws UnsupportedEncodingException{
        String charset[] = {"euc-kr", "ksc5601", "iso-8859-1", "8859_1", "ascii", "utf-8"};
            
        for(int i=0; i<charset.length ; i++){
            for(int j=0 ; j<charset.length ; j++){
                //if(i==j) continue;

      System.out.println(charset[i]+" : "+charset[j]+" :"+new String(str_kr.getBytes(charset[i]),charset[j]));
            }
        }
    }
	
	public ActionForward select( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
			Row	req			=	getRequestInfo(request);
		try{
			// 디비연결 시작
			Transaction.start(request);		

			req.put("searchType","title");
			//req.put("searchWord","네이버");
			try{
				System.out.println("searchWord:=================================1");
				charSet(req.getString("searchWord"));
				System.out.println("searchWord:=================================2");
			System.out.println("searchWord:"+(new String(req.getString("searchWord").getBytes("euc-kr"), "8859_1")));
			System.out.println("OOO_searchWord:"+req.getString("searchWord"));
			}catch(Exception e){
				e.printStackTrace();
			}
			//if(req.get("searchWord") != null){
			//req.put("searchWord", UtilMaster.toEng(req.getString("searchWord")));
			//}			
			
	        // 전체 게시물 갯수
			String totalQueryName	=	"newsMaster.selectTotal";		
			String	totalQuery 	=	mappingQuery(request, totalQueryName);
			
			simpleExecuteQueryGetOneRow(request, totalQuery, totalQueryName);
			
			Row	SUM_LIST	=	(Row)request.getAttribute(totalQueryName);
			req.put("TOTAL", SUM_LIST.getString("TOTAL"));					
			int start_row 	=	0;
			int page		=	0;
			//페이지 파라미터 점검
			//첫페이지는 파라미터가 없으므로 0이나 1로 셋팅한다.
			if(req.get("page") ==null || ((String)req.get("page")).trim().length() == 0 ){
				page	=	1;
			}else  {
				try{
					page	=	Integer.parseInt(((String)req.get("page")));
				}catch(Exception e){
					page	=	1;
				}
			}
			start_row	=	(page	-	1)	*	10;
			req.put("start_row", start_row+"");
			req.put("page", page+"");

			
			String listQueryName		=	"newsMaster.select";		
			String	listQuery 		=	mappingQuery(req, listQueryName);	
			simpleExecuteQuery(request, listQuery, listQueryName);												
	
			//디비연결 종
	        Transaction.end(request);
        
		}catch(Exception e){
			System.out.println("******"+e.getMessage());
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		}
		
		
		
		return mapping.findForward("select");
	}
	
	
	
	public ActionForward openCast( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		Row	req			=	getRequestInfo(request);
		
		
		
		
		return mapping.findForward("openCast");
	}
	
	
	
}
